package com.example.glkotlin.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.example.glkotlin.R
import com.example.glkotlin.bean.FruitBean

class FruitAdapter(private val dataList : List<FruitBean>) : RecyclerView.Adapter<FruitAdapter.ViewHolder>() {

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val image: ImageView = view.findViewById(R.id.fruit_image)
        val name: TextView = view.findViewById(R.id.fruit_name)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.home_adapter_fruit_item, parent, false)
        val viewHolder = ViewHolder(view)
        viewHolder.itemView.setOnClickListener {
            val fruit = dataList[viewHolder.adapterPosition]
            Toast.makeText(parent.context, "The ${fruit.name} is clicked, position is ${viewHolder.adapterPosition}", Toast.LENGTH_SHORT).show()
        }
        viewHolder.image.setOnClickListener {
            val fruit = dataList[viewHolder.adapterPosition]
            Toast.makeText(parent.context, "The ${fruit.name} of image is clicked, position is ${viewHolder.adapterPosition}", Toast.LENGTH_SHORT).show()
        }
        return viewHolder

    }

    override fun getItemCount(): Int {
        return dataList.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val fruitBean = dataList[position]
        holder.image.setImageResource(fruitBean.image)
        holder.name.text = fruitBean.name
    }
}